document.write(`<link href="css/lib/xtiper.css" type="text/css" rel="stylesheet" />`);
document.write(`<script type="text/javascript" src="js/lib/xtiper.min.js"></script>`);

const notification = window.__TAURI__.notification;
const dialog = window.__TAURI__.dialog;
const fs = window.__TAURI__.fs;
const trpath = window.__TAURI__.path;
const http = window.__TAURI__.http;
const t_window = window.__TAURI__.window;
const { invoke } = window.__TAURI__.tauri;

const KB = 1024;
const MB = KB * 1024;
const GB = MB * 1024;

// 本地资源服务器地址
const ASSET_URL = 'https://asset.localhost/';

async function call (func, obj) {
    return await invoke(func, obj);
}

/**
 * 将size换算为可读内存量
 * @returns {string}
 */
function mem2readable (size) {
    if (size == undefined || size == null) {
        return '0 bytes';
    }
    if (size > GB) {
        return (size / GB).toFixed(1) + ' G';
    } else if (size > MB) {
        return (size / MB).toFixed(1) + ' M';
    } else if (size > KB) {
        return (size / KB).toFixed(1) + ' K';
    } else if (size > 0) {
        return size + ' bytes';
    } else {
        return '0 bytes';
    }
}

/**
 * 上一个路径
 * @returns {string}
 */
function last_path (path) {
    if (!path) {
        return '';
    }
    let index = path.lastIndexOf('/');
    let index2 = path.lastIndexOf('\\');
    if (index == -1 && index2 == -1) {
        return '';
    }
    let indexLast = index > index2 ? index : index2;
    return path.substring(0, indexLast);
}

/**
 * 若为windows，右下角的通知
 * @param {string} msg 通知信息
 */
async function notify (msg) {
    let isPermission = await notification.isPermissionGranted();
    if (!isPermission) {
        const permission = await notification.requestPermission();
        isPermission = permission === 'granted';
    }
    if (isPermission) {
        await notification.sendNotification(msg);
    }
}

/**
 * 转换本地绝对路径
 * @param {string} path 
 * @returns 
 */
function convert_local_path (path) {
    if (!path) {
        return '';
    }
    return ASSET_URL + path.replace('file:///');
}

/**
 * 上面方法的反向方法
 * @param {string} path 
 * @returns 
 */
function local_path (path) {
    if (!path) {
        return '';
    }
    return decodeURI(path.replace(ASSET_URL, ''));
}

function get_icon (suc) {
    let icon = 's';
    switch (suc) {
        case 0:
            icon = 's';
            break;
        case 1:
            icon = 'e';
            break;
        case 2:
            icon = 'w';
            break;
        case 3:
            icon = 'a';
            break;
        case 4:
            icon = 'h';
            break;
    }
    return icon;
}

/**
 * @param {string} msg 正文
 * @param {int} 0/1/2/3/4: success/error/warning/ask/hello, 默认0
 */
function toast (msg, suc) {
    if (!msg) {
        return;
    }
    xtip.msg(msg, {
        times: 2,  // 停留时间: 2s
        type: 'b', // white
        pos: 'm',  // middle
        zIndex: 999,
        icon: get_icon(suc),
    });
}

/**
 * alert
 * @param {string} msg 正文
 * @param {int} 0/1/2/3/4: success/error/warning/ask/hello, 默认0
 * @param {int} 显示时长，秒，若为0不自动消失
 */
function show (msg, suc, times = 0) {
    if (!msg) {
        return;
    }
    xtip.alert(msg, {
        times: times,  // 停留时间: 2s
        type: 'b', // white
        pos: 'm',  // middle
        zIndex: 999,
        icon: get_icon(suc),
    });
}

/**
 * 打开loading层
 * @returns loading下标
 */
function loading () {
    let index = xtip.load('', {
        closeBtn: true
    });
    return index;
}

/**
 * 关闭loading层。若index无效，关闭所有loading层
 * @param {int} index loading下标
 * @returns 
 */
function close_loading (index) {
    xtip.close(index);
}

/**
 * 处理数组结果
 * @param {array[2]} res tauri后端返回的结果
 * @param {string} id 组件id，为其value赋值
 */
function deal_array_res (res, id) {
    console.log('deal_array_res:res=', res, 'id=', id);
    if (!Array.isArray(res) || res.length < 2) {
        return;
    }
    if (res[0] != 0) {
        toast(res[1], 1);
        return;
    }

    document.getElementById(id).value = res[1];
}


/**
 * 格式化时间
 */
Date.prototype.format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substring(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substring(("" + o[k]).length)));
    return fmt;
}

/**
 * 当前时间格式化后的
 */
function now_str () {
    return new Date().format('yyyy-MM-dd HH:mm:ss');
}

/**
 * 打开新窗口
 * @param {string} title 标题
 * @param {string} content 内容
 * @param {string} type 类型，默认html
 * @param {string} width 宽度
 * @param {string} height 高度
 * @param {bool} shadeClose 是否点击外侧关闭
 */
function open_window (title, content, type = 'html', width = '500px', height = '400px', shadeClose = true) {
    xtip.open({
        type,
        title,
        height,
        width,
        content,
        shadeClose,
    });
}
